from typing import Annotated
from datetime import datetime
from collections.abc import Callable
import logging, logging.config
import os
import yaml
from fastapi import Request
from fastapi.middleware.cors import CORSMiddleware 
from gurren.g import app, ahttpx
import gurren.recaptcha
import gurren.ws

# TODO: разобраться с FastAPI Dependes, Cookie, JWT Token
# TODO: APIRouter вместо gurren.g.app - https://fastapi.tiangolo.com/tutorial/bigger-applications/, 
#       https://stackoverflow.com/questions/70118412/keeping-endpoint-function-declarations-in-separate-modules-with-fastapi

log_conf = os.path.join(os.path.dirname(__file__), 'logging.dev.yaml')
print('LOG_CONF', log_conf)

with open(log_conf, 'r') as f_log_conf:
    logging.config.dictConfig(yaml.load(f_log_conf, Loader=yaml.FullLoader))

log = logging.getLogger(__name__)


@app.get("/")
async def home():
    return "Server API"

@app.get("/ws/issue")
async def issue(req: Request):
    captcha = req.cookies.get("x-gurren-captcha") or '?'
    return f"WebSocket {str(datetime.now())[:19]} Human - {captcha}"

#
# WOW! Example of easy proxy with httpx streaming!
#
from starlette.background import BackgroundTask
from starlette.responses import StreamingResponse

@app.get('/ws/stream')
async def stream(req: Request):
    outer_req = ahttpx.build_request("GET", "https://www.python-httpx.org/async/")
    r = await ahttpx.send(outer_req, stream=True)
    return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))
